package com.eachonline.smart.web.user;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.eachonline.core.JsonResult;
import com.eachonline.smart.mapper.SmartUserDetailMapper;
import com.eachonline.smart.model.CertificatePicture;
import com.eachonline.smart.model.CertificatePictureExample;
import com.eachonline.smart.model.SmartUser;
import com.eachonline.smart.model.SmartUserDetail;
import com.eachonline.smart.model.SmartUserDetailExample;
import com.eachonline.smart.model.WorksPhotoPicture;
import com.eachonline.smart.model.WorksPhotoPictureExample;
import com.eachonline.smart.service.CertificatePictureService;
import com.eachonline.smart.service.SmartUserService;
import com.eachonline.smart.service.UserDetailService;
import com.eachonline.smart.service.WorksPhotoPictureService;
import com.eachonline.util.StringUtil;
import com.eachonline.util.UUIDUtil;

@Controller
@RequestMapping("/cert")
public class UserCertController {
	
	private static final Logger logger =  Logger.getLogger(UserCertController.class);
	
	@Autowired
	public SmartUserService userService;
	
	@Autowired
	public WorksPhotoPictureService worksPhotoPictureService;
	
	@Autowired
	public SmartUserDetailMapper userDetailMapper;
	
	@Autowired
	public UserDetailService userDetailService;
	
	@Autowired
	public CertificatePictureService certPictureService;
	
	/**
	 * 申请用户认证
	 * @param response
	 * @param cpEntityList
	 * @param detail
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveCertificate", method = { RequestMethod.POST})
	public JsonResult saveCertificate(HttpServletRequest request,HttpServletResponse response,String worksJsonStr,String certJsonStr ,SmartUserDetail detail,String userId)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		
		if(StringUtil.isEmpty(userId))
		{
			return new JsonResult(false,"申请人的用户ID 为空");
		}
		
		
		if(StringUtil.isEmpty(certJsonStr))
		{
			return new JsonResult(false,"资质证书没有");
		}
				
		if(StringUtil.isEmpty(detail.getUserCardNo()))
		{
			return new JsonResult(false,"身份证不能为空");
		}
		
		if(StringUtil.isEmpty(detail.getUserFrontCardpic()))
		{
			return new JsonResult(false,"身份证正面没有上传");
		}
		
		if(StringUtil.isEmpty(detail.getUserVersoCardpic()))
		{
			return new JsonResult(false,"身份证反面没有上传");
		}
		
		
		if(StringUtil.isEmpty(detail.getUserRealName()))
		{
			return new JsonResult(false,"请填写用户真实姓名");
		}
		
		//上传前删除原有数据 begin
		if(StringUtil.isNotEmpty(certJsonStr))
		{
			CertificatePictureExample cpExample = new CertificatePictureExample();
			cpExample.createCriteria().andUserIdEqualTo(userId);
			List<CertificatePicture> cpList = certPictureService.selectByExample(cpExample);
			if(cpList.size()>0)
			{
				certPictureService.deleteByExample(cpExample);
			}

		}

		
		
		
		
		if(detail != null)
		{
			SmartUserDetailExample usExample = new SmartUserDetailExample();
			usExample.createCriteria().andUserIdEqualTo(userId);
			List<SmartUserDetail> udList = userDetailService.selectByExample(usExample);
			if(udList.size()>0)
			{
				userDetailService.deleteByExample(usExample);
			}
		}
		//end
		
		
		if(StringUtil.isNotEmpty(worksJsonStr))
		{
			WorksPhotoPictureExample cpExample = new WorksPhotoPictureExample();
			cpExample.createCriteria().andUserIdEqualTo(userId);
			List<WorksPhotoPicture> cpList = worksPhotoPictureService.selectByExample(cpExample);
			if(cpList.size()>0)
			{
				worksPhotoPictureService.deleteByExample(cpExample);
			}
			
			
			
			List<WorksPhotoPicture> worksPhotoList=JSON.parseArray(worksJsonStr, WorksPhotoPicture.class);
			 for (WorksPhotoPicture photoPic:worksPhotoList)
			 {
				 photoPic.setSid(UUIDUtil.getUUID());
				 photoPic.setUserId(detail.getUserId());
				 photoPic.setCreateTime(new Date());
				 worksPhotoPictureService.insert(photoPic);
			 }
			 
		}
		
		
		List<CertificatePicture> cpEntityList=JSON.parseArray(certJsonStr, CertificatePicture.class);
		
		detail.setSid(UUIDUtil.getUUID());
		detail.setCreateTime(new Date());
		try {
		   for (CertificatePicture pic:cpEntityList) {
			    pic.setSid(UUIDUtil.getUUID());
			    pic.setUserId(detail.getUserId());
				pic.setCreateTime(new Date());
				}
			 SmartUser user=userService.selectByPrimaryKey(userId);
			 user.setCheckStatus("1");
			 userService.updateByPrimaryKeySelective(user);
			 userService.appleyUserCertificate(detail, cpEntityList);
			 logger.debug("===========》申请成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult(false,"操作失败");
		}
	
		return new JsonResult(true,"操作成功");
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/updateCertificate", method = { RequestMethod.POST})
	public JsonResult updateCertificate(HttpServletResponse response,String certJsonStr,SmartUserDetail detail)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		List<CertificatePicture> cpEntityList=JSON.parseArray(certJsonStr, CertificatePicture.class);
		try {
			for (
			    CertificatePicture pic:cpEntityList) {
				pic.setCreateTime(new Date());
				if(pic.getSid()==null||pic.getSid().equals(""))
				{
					pic.setSid(UUIDUtil.getUUID());
				}
			    pic.setUserId(detail.getUserId());
				certPictureService.updateByPrimaryKeySelective(pic);
				}
			
			userDetailMapper.updateByPrimaryKeySelective(detail);
			
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult(false,"操作失败");
		}
		return new JsonResult(true,"操作成功");
	}
	
	
	
	@ResponseBody
	@RequestMapping(value = "/delCertificate", method = { RequestMethod.POST})
	public JsonResult delCertificate(HttpServletResponse response,String sid)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		try {
			certPictureService.deleteByPrimaryKey(sid);
			 
			return new JsonResult(true,"操作成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JsonResult(false,"操作失败");
	}
	
	

	@ResponseBody
	@RequestMapping(value = "/userCertificateInfo", method = { RequestMethod.POST})
	public JsonResult userCertificateInfo(HttpServletResponse response,String userId)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		Map<String,Object> map = new HashMap<String, Object>();
		CertificatePictureExample example = new CertificatePictureExample();
		example.createCriteria().andUserIdEqualTo(userId);
		List<CertificatePicture> cerList = certPictureService.selectByExample(example);
		
		SmartUserDetailExample userdetailExample=new SmartUserDetailExample();
		userdetailExample.createCriteria().andUserIdEqualTo(userId);
		
		List<SmartUserDetail> userDetailList = userDetailMapper.selectByExample(userdetailExample);

		if(userDetailList==null||userDetailList.size()==0)
		{
			map.put("userDetail", null);
			
		}else{
			map.put("userDetail", userDetailList.get(0));
		}
		
		map.put("certificateList", cerList);
		return new JsonResult(true,map);
	}

	/**
	 * 审核用户认证
	 * @param response
	 * @param cpEntityList
	 * @param detail
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/isAgreeUserCertificate", method = { RequestMethod.POST})
	public JsonResult isAgreeUserCertificate(HttpServletResponse response,String userId,String status,String comment)
	{
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
	    SmartUser user=userService.selectByPrimaryKey(userId);
	    user.setCheckStatus(status);
	    userService.updateByPrimaryKeySelective(user);
	
		return new JsonResult(true,"成功");
	}

}
